package com.cloud.mkz.gateway.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
import reactor.core.publisher.Mono;

/**
 * @author SpringCloud
 * @date 2019/2/1 路由限流配置
 */
@Configuration
@EnableConfigurationProperties(GlobalCorsProperties.class)
public class RateLimiterConfiguration {

	@Bean(value = "remoteAddrKeyResolver")
	public KeyResolver remoteAddrKeyResolver() {
		return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
	}

	@Order(Ordered.HIGHEST_PRECEDENCE)
	@RefreshScope
	@Bean
	public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties){
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
		globalCorsProperties.getCorsConfigurations().forEach(source::registerCorsConfiguration);
		return new CorsWebFilter(source);
	}
}
